/**
 * Created by Dalyn on 2017/5/4.
 */
import React from "react";
import {hashHistory} from 'react-router';
import { Table, message, DatePicker  } from 'antd';
import Relay from 'react-relay';
import Reactkey from "../../util/ReactKey"
import Util from '../../util/Util.js'
import ProductionProcessDetailMutation from './mutation/ProductionProcessDetailMutation';
import SaveProductProcessMutation from './mutation/saveProductProcessMutation';

import "./css/productionManagement_process.css";
import "./css/productionManagement_common.css";
import moment from 'moment';
const { RangePicker } = DatePicker;

import {Button} from 'fly';

// 推荐在入口文件全局设置 locale
import 'moment/locale/zh-cn';
moment.locale('zh-cn');


export default class ProductionUpdateProcess extends React.Component {
    constructor(){
        super();
        this.state={
          dataSource: [],
          context:{
            cutQua:''
          },
        }
        let gid =  ''
        let orderId = ''
        let quality = ''
        let styleNo = ''
        let partBname = ''
    }
    componentWillMount() {
      this.getProductProcess()
    }

    getProductProcess() {
      Relay.Store.commitUpdate(
          new ProductionProcessDetailMutation({
              gId: this.props.location.state.gid
          }),
          {
              onFailure: () => {
                  message.info("请求失败")
              },
              onSuccess: (response) => {
                let errorCode = response.getproductProcessDetail.getproductProcessDetail.errorCode
                if(errorCode == 0) {
                  let dataSource = response.getproductProcessDetail.getproductProcessDetail.productProduceDetails
                  // let totalResult = response.productProduceDetails.productProduceDetails.totalResult
                  dataSource.push({
                      creatList: Reactkey.key,
                      produceDate: null,
                      packQua: "",
                      afterQua: '',
                      sewQua: '',
                      cutQua: ''
                    },{gid: 'key2'},{gid: 'key3'},{gid: 'key4'})
                  // if (dataSource.length) {
                  //   let lastDate = Util.timeStamp(dataSource[dataSource.length - 1].produceDate)  //最后一条数据，时间戳格式
                  //   let TIME = Util.timeStamp(Util.dateFormat(new Date()))
                  //
                  //   // while(lastDate != TIME) {
                  //     lastDate += parseInt(86400000)
                  //     dataSource.push({
                  //       creatList: Reactkey.key,
                  //       produceDate: '',
                  //       packQua: "",
              		// 			afterQua: '',
              		// 			sewQua: '',
              		// 			cutQua: ''
                  //     })
                  //   }
                  //   // if (lastDate == TIME) {
                  //   //   let isCreatList = dataSource[dataSource.length - 1].creatList
                  //   //   if (!isCreatList) {
                  //   //     dataSource.push({
                  //   //       creatList: Reactkey.key,
                  //   //       produceDate: Util.dateFormat(lastDate),
                  //   //       packQua: "",
                	// 	// 			afterQua: '',
                	// 	// 			sewQua: '',
                	// 	// 			cutQua: ''
                  //   //     })
                  //   //   }
                  //   // }
                  // } else {
                  //     dataSource.push({
                  //       creatList: Reactkey.key,
                  //       produceDate: Util.dateFormat(new Date()),
                  //       packQua: "",
              		// 			afterQua: '',
              		// 			sewQua: '',
              		// 			cutQua: ''
                  //     })
                  // }
                  //   dataSource.push({
                  //     creatList: Reactkey.key,
                  //     produceDate: Util.dateFormat(new Date()),
                  //     packQua: "",
                  //     afterQua: '',
                  //     sewQua: '',
                  //     cutQua: ''
                  //   },{gid: 'key2'},{gid: 'key3'},{gid: 'key4'})
                  if (dataSource) {
                    this.setState({
                      dataSource: dataSource,
                    })
                  }
                }
              }

          }
      );
    }

    saveProductProcess() {
      let jsonArgs = [],dateFlag = true, dataSourceFlag = true;

      this.state.dataSource.map((v, i ,ele) =>{
          if (!v.produceDate && v.creatList) {
             dateFlag = false   //如果是新创建的且日期不为空
          } else if (v.produceDate && v.creatList){
             dateFlag = true
          }
         if (v.creatList && (v.cutQua != '' || v.packQua != '' || v.sewQua != '' || v.afterQua != '' )) {
            let json = {
                gid: this.props.location.state.gid,
                produceDate: v.produceDate,
                cutQua: v.cutQua,
                sewQua: v.sewQua,
                afterQua: v.afterQua,
                packQua: v.packQua
              }
            jsonArgs.push(json)
            dataSourceFlag = true
        } else if (v.creatList && v.cutQua == '' && v.packQua == '' && v.sewQua == '' && v.afterQua == ''){
          dataSourceFlag = false
        }
      });

      if (!dateFlag) {
        message.info('请选择日期')
        return
      }

      if (!dataSourceFlag) {
        message.info('请填写完整数据')
        return
      }
      if (jsonArgs.length) {
        Relay.Store.commitUpdate(
            new SaveProductProcessMutation({
                jsonArgs: JSON.stringify(jsonArgs)
            }),
            {
                onFailure: () => {
                    message.info("请求失败")
                },
                onSuccess: (response) => {
                  let errorCode = response.productProcess.productProcess.errorCode
                  if (errorCode == 0) {
                    message.success('保存成功')
                    this.getProductProcess()
                    // hashHistory.push("/ProductionProcess/")
                  }
                }

            }
          )
      } else {
        message.info('请填写完整数据')
        return
      }
    }

    //删除按钮删除一行
    onDelete = (index) => {
      const dataSource = [...this.state.dataSource];
      dataSource.splice(index, 1);
      this.setState({
        dataSource,
      });
    }
    //点击添加按钮添加一行
    handleAdd = () => {
      const { dataSource } = this.state;
      const newData = {
        creatList: Reactkey.key,
        produceDate: '',
        packQua: "",
        afterQua: '',
        sewQua: '',
        cutQua: ''
      };
      dataSource.splice(dataSource.length - 3, 0, newData )
      this.setState({
        dataSource
      });
    }

    InputChange(contextname,produceDate,index,e){
      let dataSource = this.state.dataSource;
      if(!dataSource[index]){
        dataSource[index] = {}
      }
      let text = e.target.value;
      let rulenum = /^[0-9]{0,10}$/;
      if (!rulenum.test(text)) {
        // message.info('不能超过10位且为正整数')
        return
      }
      let context = dataSource[index];
      // context['gId'] = this.props.location.state.gid;
      context[contextname] = text.substring(0,10);
      this.setState({
          context: context,
          dataSource: dataSource
      });
    }

    sumTotal(type) {
      let sumTotal = 0
      this.state.dataSource.map((v,i) =>{
        if (type == 'cutQua' && v.cutQua != undefined && v.cutQua != '') {
          sumTotal += parseFloat(v.cutQua)
        } else if (type == 'sewQua' && v.sewQua != undefined && v.sewQua != '') {
          sumTotal += parseFloat(v.sewQua)
        } else if (type == 'afterQua' && v.afterQua != undefined && v.afterQua != '') {
          sumTotal += parseFloat(v.afterQua)
        } else if (type == 'packQua' && v.packQua != undefined && v.packQua != '') {
          sumTotal += parseFloat(v.packQua)
        }
      })
      return sumTotal
    }

    _dateChange(index, value, dateString) {
      let dataSource = this.state.dataSource;
      if(!dataSource[index]){
        dataSource[index] = {}
      }
      let context = dataSource[index];
      context['produceDate'] = dateString
      this.setState({
        dataSource
      },()=>{
        console.log(this.state.dataSource);
      })
    }
    disabledDate(index, current){
      if (index == 0) {
        return current && current.valueOf() < Date.now() - 86400000*365;
      } else {
        return current && current.valueOf() < Number(Util.timeStamp(this.state.dataSource[index-1].produceDate))+86400000;
      }
    }
    render(){
      let quality = this.props.location.state.quality
      const columns = [
        {
          title: '日期',
          dataIndex: 'produceDate',
          width: 218,
          className:'process_detail_datepicker',
          render: ((text, record, index) => {
            if (record.creatList) {
              // return record.produceDate
              return (
                <DatePicker
                  format="YYYY-MM-DD"
                  placeholder="请选择时间"
                  onChange={this._dateChange.bind(this, index)}
                  disabledDate={this.disabledDate.bind(this,index)}
                />
              )
            } else if (index == this.state.dataSource.length-3) {
              return '总计'
            } else if (index == this.state.dataSource.length-2) {
              return '欠数'
            } else if (index == this.state.dataSource.length-1) {
              return '完成比例'
            } else {
              return record.produceDate
            }
          })
        },
        {
          title: '裁剪数',
          className: 'cutQua',
          dataIndex: 'cutQua',
          width: 218,
          render: ((text, record, index) => {
            if (record.creatList) {
              return <input className="prodution_update_progress_input_edit"  value={record.cutQua} onChange={this.InputChange.bind(this,'cutQua',record.produceDate,index)} type="text" />
            } else if (index == this.state.dataSource.length-3) {
              return this.sumTotal('cutQua')
            } else if (index == this.state.dataSource.length-2) {
              let sumTotal = this.sumTotal('cutQua')
              return (quality - sumTotal)
            } else if (index == this.state.dataSource.length-1) {
              let sumTotal = this.sumTotal('cutQua')
              if(quality != 0) {
                return ((sumTotal/quality*100).toFixed(2)+'%' || 0)
              } else {
                return '-'
              }
            } else {
              return record.cutQua
            }
          })
        },
        {
          title: '缝制数',
          className: 'sewQua',
          dataIndex: 'sewQua',
          width: 218,
          render: ((text, record, index) => {
            if (record.creatList) {
              return <input className="prodution_update_progress_input_edit"  value={record.sewQua} onChange={this.InputChange.bind(this,'sewQua',record.produceDate,index)} type="text" />
            } else if (index == this.state.dataSource.length-3) {
              return this.sumTotal('sewQua')
            } else if (index == this.state.dataSource.length-2) {
              let sumTotal = this.sumTotal('sewQua')
              return (quality - sumTotal)
            }  else if (index == this.state.dataSource.length-1) {
              let sumTotal = this.sumTotal('sewQua')
              if(quality != 0) {
                return ((sumTotal/quality*100).toFixed(2)+'%' || 0)
              } else {
                return '-'
              }
            } else {
              return record.sewQua
            }
          })
        },
        {
          title: '后整数',
          dataIndex: 'afterQua',
          width: 218,
          render: ((text, record, index) => {
            if (record.creatList) {
              return <input className="prodution_update_progress_input_edit"  value={record.afterQua} onChange={this.InputChange.bind(this,'afterQua',record.produceDate,index)} type="text" />
            } else if (index == this.state.dataSource.length-3) {
              return this.sumTotal('afterQua')
            } else if (index == this.state.dataSource.length-2) {
              let sumTotal = this.sumTotal('afterQua')
              return (quality - sumTotal)
            }  else if (index == this.state.dataSource.length-1) {
              let sumTotal = this.sumTotal('afterQua')
              if(quality != 0) {
                return ((sumTotal/quality*100).toFixed(2)+'%' || 0)
              } else {
                return '-'
              }
            } else {
              return record.afterQua
            }
          })
        },
        {
          title: '包装数',
          dataIndex: 'packQua',
          width: 218,
          render: ((text, record, index) => {
            if (record.creatList) {
              return <input className="prodution_update_progress_input_edit"  value={record.packQua} onChange={this.InputChange.bind(this,'packQua',record.produceDate,index)} type="text" />
            } else if (index == this.state.dataSource.length-3) {
              return this.sumTotal('packQua')
            } else if (index == this.state.dataSource.length-2) {
              let sumTotal = this.sumTotal('packQua')
              return (quality - sumTotal)
            }  else if (index == this.state.dataSource.length-1) {
              let sumTotal = this.sumTotal('packQua')
              if(quality != 0) {
                return ((sumTotal/quality*100).toFixed(2)+'%' || 0)
              } else {
                return '-'
              }
            } else {
              return record.packQua
            }
          })
        },
      ];

        return (
          <div className='production_manage_process_box'>
            <Table
              columns={columns}
              dataSource={this.state.dataSource}
              bordered
              pagination={false}
              className="order_table production_management_process_table"
              title={() => {
                return (<span>&nbsp;订单编号：{this.props.location.state.orderId || ''}&nbsp;&nbsp;&nbsp;
                客户：{this.props.location.state.partBname || ''}&nbsp;&nbsp;&nbsp;
                款号：{this.props.location.state.styleNo || ''}
                <a style={{float:'right',color: 'red',fontSize:'12px'}}>请谨慎填写，一旦保存不可修改，保存后自动新增一行</a></span>)
              }}
            />
          <div className="production_management_publish">
              <Button onClick={this.saveProductProcess.bind(this)}>保存</Button>
          </div>
          </div>
        )
    }
}
